package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.domain.ShoppingCar;
import com.cyzy.dto.ResponseData;
import com.cyzy.service.ShoppingCarService;
import com.cyzy.mapper.ShoppingCarMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 10204
 * @description 针对表【shopping_car(购物车表，用于存储用户购物车的信息)】的数据库操作Service实现
 * @createDate 2024-11-27 09:59:25
 */
@Service
public class ShoppingCarServiceImpl extends ServiceImpl<ShoppingCarMapper, ShoppingCar> implements ShoppingCarService {
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Override
    public ResponseData addCar(ShoppingCar shoppingCar) {
        QueryWrapper<ShoppingCar> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", shoppingCar.getUserId())
                .eq("goods_name", shoppingCar.getGoodsName());
        ShoppingCar existingCar = shoppingCarMapper.selectOne(wrapper);
        int a=Integer.parseInt(shoppingCar.getGoodsNum())  +Integer.parseInt(existingCar.getGoodsNum()) ;
        String num=String.valueOf(a);
        if (existingCar != null) {
            existingCar.setGoodsNum(num);
            int updateResult = shoppingCarMapper.updateById(existingCar);
            if (updateResult > 0) {
                return ResponseData.ok2("商品数量已更新");
            } else {
                return ResponseData.no2("更新失败");
            }
        } else {
            int insertResult = shoppingCarMapper.insert(shoppingCar);
            if (insertResult > 0) {
                return ResponseData.ok2("商品已添加到购物车");
            } else {
                return ResponseData.no2("添加失败");
            }
        }
    }

    @Override
    public ResponseData findCar(String userId) {
        List<ShoppingCar> cars = shoppingCarMapper.findCar(userId);
      return ResponseData.ok2(cars);
    }
}





